<!-- AI动态表单 -->
<template>
  <div v-if="formData.length > 0" class="ai-form-mid bg-white rounded-[8px]" :class="{wapon: datas.midShow, ani:datas.midShowDelay}">
    <!-- 手机端拉起和收起的展示按钮 -->
    <div class="wap wap-open-icon" @click="toggleBox" :class="{on : !datas.midShow}">
      <icon name="el-icon-ArrowDownBold" color="#000" /><span class="txt">编辑</span>
    </div>
    <div v-if="formData" class="midShowCon wap" @click="toggleBox" :class="{on : datas.midShow}">
      <div class="text-line2 show-title">{{formData[0].val}}</div>
      <span class="text-tx-secondary" v-if="formData[0].val === ''">请输入您想要咨询的问题</span>
    </div>
    <slot name="top"></slot>
    <!-- 表单   item.id类型:1文本 2多行文本 3 单选4 多选 5下拉选择 6-地址选择 -->
    <el-form v-if="formData" ref="formRef" :model="formData" class="zb-form">
      <el-scrollbar height="100%" ref="scrollbarRef">
        <el-form-item v-for="(item, index) in formData" :key="index" :label="item.title" :prop="item.key || ''" :class="{isRequire: item.require === 1}">
          <el-input v-if="item.id == 1" type="text" :placeholder="formtips(item)" v-model="item.val" />
          <el-input v-else-if="item.id == 2" :rows="item.rows" type="textarea" :autosize="{ minRows: index === 0 ? 6 : 3, maxRows: 1000 }" :placeholder="formtips(item)" v-model="item.val"  />
          <el-radio-group v-else-if="item.id == 3" :placeholder="formtips(item)" v-model="item.val">
            <el-radio v-for="listItem in item.choose" :key="listItem" :value="listItem">{{listItem}}</el-radio>
          </el-radio-group>
          <el-checkbox-group v-else-if="item.id == 4" :placeholder="formtips(item)" v-model="item.val">
            <el-checkbox v-for="listItem in item.choose" :key="listItem" :label="listItem" :value="listItem"></el-checkbox>
          </el-checkbox-group>
          
          <el-select v-else-if="item.id == 5" class="w100" :filterable="bodyW < 769 ? false : true" :placeholder="formtips(item)" v-model="item.val">
            <el-option v-for="listItem in item.choose" :key="listItem" :label="listItem" :value="listItem" />
          </el-select>
          <!-- 地址 -->
          <template v-else-if="item.id == 6 && addressData">
            <zb-address ref="addressRef" :data="addressData" :cur="address" :keys="addresskey" @confirm="addressConfirm($event, index)" />
          </template>
          <el-date-picker v-else-if="item.id == 7" class="w100" v-model="item.val" type="date" :placeholder="formtips(item)" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
          <div v-else-if="item.id == 99" class="moreImgs flex flex-wrap">
            <div v-for="(imgitem, imgidx) in item.val" :key="imgidx" class="avatar-uploader relative">
              <img :src="imgitem" alt="">
              <div class="hover"><span class="sp" @click="delImgFun(index, imgidx)">删除</span><span class="sp" @click="showImgFun(imgitem)">查看</span></div>
            </div>
            <el-upload multiple class="avatar-uploader" :action="actionsrc" :show-file-list="false" :on-success="(file: any, fileList: any[]) => handleSuccess(file, fileList, index)" accept=".jpg,.png,.gif,.jpeg">
              <div class="avatar-uploader-icon flex items-center justify-center">
                <div>
                  <icon name="el-icon-Plus" :size="20" />
                  <p>添加</p>
                </div>
              </div>
            </el-upload>
          </div>
          <div v-if="!item.val && item.show == 1" class="showtip">{{formtips(item)}}</div>
          <div v-if="item.val && item.test === 1 && mobileTest(item.val)" class="showtip">手机号格式不正确</div>
        </el-form-item>
        <!-- 底部按钮 -->
        <div class="bottom-box">
          <el-button type="primary" :loading="datas.loading" :disabled="formData[0].length === 0" @click="submit" size="large" class="submit-btn">
            <template v-if="detail.submit === 'json'">提交</template>
            <template v-else-if="datas.buildOk">重新生成</template>
            <template v-else>生成内容</template>
          </el-button>
        </div>
      </el-scrollbar>
    </el-form>
  </div>
  <!-- 手机端背景 -->
  <div v-if="datas.midShow" class="mid-bg wap fadeIn" @click="toggleBox"></div>
  
  <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { getAreaApi, uploadApi } from '@/api/app'
import { loginShow } from '@/utils/weChat'
const actionsrc = uploadApi;
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
const p1 ="请输入"
const p2 ="请选择"
const p3 ="请上传"
const props = defineProps({
  addresskey:{
    type:String,
    default:'id', // 地址的传值
  }
})

const formtips = (item:any) => {
  const befores = item.id == 1 || item.id == 2 ? p1 + item.title : item.id === 99 ? p3 + item.title : p2 + item.title
  return item.tips ? `${item.tips}` : `${befores}`
}
const dialogVisible = ref(false); // 放大图片
const dialogImageUrl = ref('')
const showImgFun = (s:string) => {
  dialogVisible.value = true;
  dialogImageUrl.value = s
}
const delImgFun = (index:number, idx:number) =>{
  formData.value[index].val = formData.value[index].val.filter((n, i) => i != idx)
}
// 地址
const addressRef = ref();

const address = reactive({
  ids:[],
  text:'',
})

// 获取省市区
const addressData = ref()
const getAear = () => {
  getAreaApi().then(res=>{
    addressData.value = res;
  })
}
const addressConfirm = (e:any, index:number)=>{
  address.ids = e.ids;
  address.text = e.text;
  formData.value[index].val = e.text
}



// 表单数据
const formData = ref<any>([]);
// 表单验证

const detail = ref();
// 其他数据
const datas = reactive({
  buildOk:false, // 生成成功
  loading:false, // 接口请求成功
  midShow: true, // 手机端显示表单
  midShowDelay: false, // 手机端显示表单 -- 为了处理键盘被拉起时处理的弹框动态变化
})
const toggleBox = () =>{
  datas.midShowDelay = true;
  datas.midShow = !datas.midShow;
  setTimeout(()=>{
    datas.midShowDelay = false;
  },500)
}

// 初始化表单
const initFormData = (data:any) => {
  // console.log('初始化表单-----initFormData', data.json)
  formData.value = data.json;
  detail.value = {...data};
  datas.buildOk = false;
  datas.loading = false;
  if(data.json.find((n:any) => n.id == 6)){
    getAear()
  }
  // console.log('初始化表单-----initFormData', formData.value)
}
// 表单提交
const emits = defineEmits(['submit'])
const submitMsg = ref();
const formRef = ref()


const mobileTest = (val:string) => {
  const phoneReg = /^1[3-9]\d{9}$/; // 手机号正则表达式
  return !phoneReg.test(val)
}
const submit = async () =>{
  // 校验必填项
  if( !loginShow() ) return; // 没有登录直接不执行后面逻辑
  console.log('loginShow--------', loginShow)
  let needTest = false;
  if(detail.value.submit === 'json'){
    datas.buildOk = false;
    formData.value = formData.value.map((n:any) =>{
      if(!n.val && n.require == 1){
        n.show = 1;
        needTest = true;
      } else if (n.val && n.require == 1 && n.test == 1 && mobileTest(n.val)) {
        n.show = 1;
        needTest = true;
      }else{
        n.show =  0
      };
      return n
    })
  }
  if(needTest) return;
  if(detail.value.submit === 'json'){
    submitMsg.value = {}
    formData.value.forEach((n:any) => {
      if(n.id == 99){
        submitMsg.value[n.key] = Array.isArray(n.val) ? n.val.join(',') : n.val
      }else{
        submitMsg.value[n.key] = n.val;
      }
    })
    if(props.addresskey === 'id'){
      submitMsg.value = {...submitMsg.value, ...address.ids}
    }
  }else{
    submitMsg.value = '';
    formData.value.forEach((n:any, i:number) => {
      const val = Array.isArray(n.val) ? n.val.join('/') : n.val
      console.log('val====', val)
      if(i === 0){
        submitMsg.value+=`$$:[${val}]`
      }else{
        submitMsg.value+=`:[${val}]`
      }
    })
  }
  console.log('---表单提交的数据', submitMsg.value);
  datas.loading = true;
  toggleBox();
  emits('submit', {msg: submitMsg.value, ok: datas.buildOk})
}
const closepup = () => {
  toggleBox();
  datas.loading = false;
}
const handleSuccess = (res: any, fileList: any[], index: number) =>{
  console.log('file', res, fileList)
    
    console.log('response---', res)
    if (res && res.code === 1) {
      if (!formData.value[index].val) {
        formData.value[index].val = [];
      }
      formData.value[index].val.push(res.data.fullurl);
  
// 引入 ElMessage

      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error('图片上传失败，请重试');
    }
  
}

// 接口请求成功后的处理逻辑
const ok = () => {
  datas.loading = false;
  datas.buildOk = true;
}
const ing = () => {
  datas.loading = true;
  datas.buildOk = false;
}




defineExpose({
  initFormData,
  closepup,
  ok,
  ing
})
</script>

<style lang="scss" scoped>
$uploadW:80px;
$hvH: calc(var(--vh, 1vh) * 100);
.avatar-uploader {
  width: $uploadW;
  height: $uploadW;
  display: flex; align-items: center; justify-content: center; margin: 0 10px 10px 0; border-radius: 4px; overflow: hidden;
  .hover{
    position: absolute; left: 0; width: 100%; bottom: 0; background-color: rgba(0,0,0,0.5); line-height: 20px; color: #fff; text-align: center; font-size: 12px; display: flex; align-items: center;
    .sp{cursor: pointer; width: 50%;}
    &::after{width: 1px; height: 60%; background-color: #fff; position: absolute; left: 50%; content: '';}
  }
  img{width: 100%; height: 100%; }
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .avatar-uploader-icon {
      color: #8c939d;
      width: calc( $uploadW - 2px ); line-height: 1.2;
      height: calc( $uploadW - 2px );
      text-align: center;
    }
  }
  
  
}
.ai-form-mid{
  overflow: hidden; width: 100%;
  .title{height: 47px;display: flex; align-items: center; padding: 0 20px; background-color: #F0F0F0; margin-bottom: 15px;}
  .zb-form{height:calc($hvH - 80px); }
  .tip{
    height: 32px;display: flex; align-items: center; margin-bottom: 6px;
    img{height: 32px;margin-left:-6px}
  }
  .bottom-box{
    padding-bottom: 10px;
    .submit-btn{width: 100%; height: 40px; border-radius: 10px;}
  }
  :deep(.el-form){
    .el-cascader{width: 100%; display: block;}
    .el-form-item{display: block;}
    .isRequire .el-form-item__label::before{content: '*'; color: #fd3535; margin-right: 3px;}
    .el-form-item__label{display: block;}
    .el-textarea__inner,.el-input__wrapper,.el-select__wrapper{
      background-color: #F9F9F9; box-shadow: none; border:1px solid #E8E8E8; border-radius: 10px; resize: none;
      &.is-focus{border:1px solid var(--el-color-primary);}
    }
    .el-select__input, .el-input{height: 50px;}
    .el-select__wrapper{padding-top: 0; padding-bottom: 0;}
  }
  .showtip{position: absolute; left: 0; top: 100%; margin-top: -5px; font-size: 12px; color: #fd3535;}
}

@media only screen and (max-width: 869px){
  .ai-form-mid{ width:280px}
}



$topH:calc($hvH - 80px);
@media only screen and (max-width: 769px){
  .show-title{font-size: 0.32rem;}
  .ai-form-mid{ 
    width:100%; margin-right:0px; position:fixed; border-radius:0px; left:0; bottom:0; z-index: calc( var(--zindex1) + 1); border-radius: 10px 10px 0 0;box-shadow: 0px 0px 8px rgba(0,0,0,0.25); max-height: $topH; transform: translateY(calc( 100% - 100px ));
    &.ani{transition: all ease 0.3s;}
    .tip{
      font-weight: bold; font-size: 0.32rem; line-height: 1; height: 0.63rem;
      img{height: 0.63rem;}
    }
    &.wapon{transform: translateY(0%)}
    .title{display: none;}
    .midShowCon{
      padding: 0 var(--wap-pad); margin: var(--wap-pad) 0; height: 80px;
      &.on{display: none !important;}
    }
    :deep(.el-form){
      height: calc($hvH - 180px); padding: 0;
      .el-form-item{margin-bottom: 0.32rem; display: block;}
      .el-form-item__label{display: block;}
      .el-textarea__inner{background-color: #F7F7F7; font-size: 0.28rem; box-shadow: none !important; border-radius: 0.24rem; padding: 0.24rem 0.3rem;}
      .el-select__input, .el-input{height: 0.8rem; width: 100%; display: flex;}
      .web{display: none !important;}
      
    }
    .zb-form{
      
      
    }
    .wap-open-icon{
      display: flex; align-items: center; justify-content: center; height: 0.5rem; width: 1.36rem; margin:0.06rem auto 0; border-radius: 0.36rem;
      .txt{display: none; margin-left: 0.12rem;}
      :deep(.el-icon){font-size: 0.34rem !important;}
      &.on{
        background-color: #F5F5F5; margin-top:6px;
        .txt{display: block;}
        :deep(.el-icon){transform: rotate(180deg);}
      }
    }
  }
  .mid-bg{display: block;position: fixed; left: 0; top: 0;z-index: var(--zindex1); background-color: rgba(0,0,0,0.5); width: 100%; left: 0; height: 100%; opacity: 0;}
  .submit-btn{width:100%}
}
</style>